package com.zhh.shiro;

import com.zhh.common.redis.RedisClient;
import com.zhh.jwt.JWTUtil;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

import java.util.Collection;
import java.util.Set;

public class CustomCache<K,V> implements Cache<K,V> {

    private final static int shiroCacheExpireTime = 3600*24*3 ;

    private final static String  PREFIX_SHIRO_CACHE = "JWT-SESSION-";

    private RedisClient redis;

    private JWTUtil jwtUtil;

    public void setRedisAndJWTUtil (RedisClient redis,JWTUtil jwtUtil){
        this.redis = redis;
        this.jwtUtil = jwtUtil;
    }

    private String getKey(Object key) {
        return PREFIX_SHIRO_CACHE + jwtUtil.getUsername(key.toString());
    }


    /**
     * 獲取緩存
     */
    @Override
    public Object get(Object key) throws CacheException {
        if (!redis.hasKey(this.getKey(key))) {
            return null;
        }
        return redis.get(this.getKey(key));
    }

    /**
     * 保存緩存
     */
    @Override
    public Object put(Object key, Object value) throws CacheException {
        // 設置Redis的Shiro緩存
        return redis.set(this.getKey(key), value, shiroCacheExpireTime);
    }

    /**
     * 移除緩存
     */
    @Override
    public Object remove(Object key) throws CacheException {
        if (!redis.hasKey(this.getKey(key))) {
            return null;
        }
        redis.del(this.getKey(key));
        return null;
    }

    /**
     * 清空所有緩存
     */
    @Override
    public void clear() throws CacheException {
        // TODO Auto-generated method stub

    }

    /**
     * 緩存的個數
     */
    @Override
    public Set<K> keys() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 獲取所有的key
     */
    @Override
    public int size() {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * 獲取所有的value
     */
    @Override
    public Collection<V> values() {
        // TODO Auto-generated method stub
        return null;
    }
}
